var app = getApp();
const innerAudioContext = app.globalData.innerAudioContext; //引入音频播放器
const recorder = app.globalData.recorder; //引入录音对象
import { tool, api, mta } from '../../../../utils/quoteConfig.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        scrollTop: 0,
        animation: null, //引导页动画
        isShowGuidance: true, //是否显示引导页
        // isBackOnNext: false,//是否从结果页面返回
        imgUrl: app.globalData.imgUrl,
        oneSecondTime: 0, //长按时间
        isShowLoading: false,
        talkIndex: 0, //当前播放或录音的句子
        isRobotSay: true, //当前角色
        timeKeeping: 0, //记录录音时长
        isShowTip: false, //是否通关完毕
        // isShowEndTip: false, //任务结束弹窗
        isShowChangeUserTip: false, //角色交换提示
        time: 5, //倒计时三秒
        isBrang: app.globalData.isBrang,
        selectData: ['listen 听', 'answer 答', 'talk 说'],
        selectIndex: 0, //听答说的类型
        listenIndex: 0, //听页面当前播放音频的序数
        titleIndex: null, //点击的为第几道题目
        answerInfo: [], //用户答案的正确情况
        trueArr: [], //后台返回的答案的数组 跟下面的对比
        userAnswer: [], //用户选择的答案 和控制开始测试按钮的状态 跟上面的对比
        isCanTest: false, //是否可以开始测试
        isBeginTest: false,
        isLongTap: false, //是否长按
        score: null, //录音得分
        talkData: null, //听的数据
        listenData: null, //答的数据
        selectQuestion: null, //说的数据
        userInfo: app.globalData.userInfo
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        mta.Page.init(); //初始化腾讯埋点
        console.log('****', app.globalData.userInfo)
        var that = this
        that.endTip = this.selectComponent("#endTip");
        console.log(options)
      
    },
    onReady: function() {
        var that = this
        tool.checkRecord()
        //音频播放器状态
        that.innerAudioContextSop()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        var that = this
        //从结果页面返回
        if (app.globalData.isBack) {
            console.log('执行了')
            that.setData({
                selectIndex: 2,
                isShowChangeUserTip: true,
                // isBackOnNext: true,
                isShowGuidance: false,
                talkIndex: 0, //当前播放或录音的句子
                isRobotSay: true, //当前角色
                score: 0,
            })
            // that.countDowm()
            //音频播放器状态
            that.innerAudioContextSop()
        } 
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {
        if (this.data.selectIndex != 2){
            console.log('停止音频播放')
            innerAudioContext.stop();
        }
        console.log(1)
        clearTimeout(this.data.bugTimeout)
        app.globalData.isBack = false
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        console.log(2)

        innerAudioContext.stop();
        clearTimeout(this.data.bugTimeout)
        app.globalData.isBack = false
    },


    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

        return {
            path: 'pages/indexPackage/index/index',
            success: function (res) {
                console.log('转发成功', res);
            },
            fail: function (err) {
                console.log('转发失败', err)
            }
        }
    },
    //图片404时候的处理
    imgLoadErr:function(e){
        console.log(e,'加载失败')
        var index = e.currentTarget.dataset.number
        var that=this
        var str = that.data.listenData[index].RoleImgUrl
        var str2 = that.data.talkData[index].RoleImgUrl
        var str1 = str.replace('/Img/', '/TempImg/')
        var str3 = str2.replace('/Img/','/TempImg/')
        console.log('++++++',str,str1)
        var arrData = 'listenData[' + index + '].RoleImgUrl'
        var arrData1 ='talkData['+index+'].RoleImgUrl'
        // that.data.talkData[index].RoleImgUrl
        that.setData({
            [arrData]: str1,
            [arrData1]: str3
        })
        
    },
    //开始任务
    beginTask:function(){
        var that=this
        that.getTaskFourData()
        tool.checkRecord()
        that.setData({
            isShowGuidance: false,
        })
    },
    //监听银音频结束事件
    innerAudioContextSop: function() {
        innerAudioContext.onEnded((res) => {
            console.log('音频结束播放+++', res)
            var that = this
            //听说页面的音频结束区别
            //监听listen 听的结束
            if (that.data.selectIndex == 0) {
                setTimeout(() => {
                    if (that.data.listenIndex < that.data.listenData.length - 1) {
                        var listenIndex = that.data.listenIndex + 1
                        that.setData({
                            listenIndex: listenIndex,
                            scrollTop: 125 * listenIndex
                        })
                        console.log(that.data.scrollTop)
                        // innerAudioContext.src = app.globalData.audioUrl + that.data.listenData[that.data.listenIndex].AudioAddress
                        innerAudioContext.src = that.data.listenData[that.data.listenIndex].AudioAddress
                        innerAudioContext.play()
                    } else {
                        that.setData({
                            selectIndex: that.data.selectIndex + 1
                        })
                    }
                }, 500)
                //监听talk 说的结束
            } else if (that.data.selectIndex == 2) {
                //数据长度为单的时候
                if (that.data.listenData.length % 2 == 1) {
                    console.log('数据长度为单数的时候')
                    if (that.data.talkIndex < that.data.listenData.length - 1) {
                        that.setData({
                            talkIndex: that.data.talkIndex + 1,
                            isRobotSay: !that.data.isRobotSay,
                        }, () => {
                            //只提示一遍
                            if (that.data.talkIndex < 2) {
                                that.setData({
                                    isShowChangeUserTip: true,
                                })
                                that.countDowm()
                            } else {
                                console.log('不在显示倒计时')
                            }
                        })
                    } else {
                        wx.showLoading({
                            title: '正在评分...',
                        })
                        var score = parseInt(that.data.score * 2 / (that.data.talkData.length - 1))
                        var bugTimeout = setTimeout(() => {
                            wx.navigateTo({
                                url: '/pages/taskPackage/pages/taskFourResult/taskFourResult?score=' + score,
                            })
                            innerAudioContext.offEnded()
                        }, 1200)

                    }
                    //数据长度为双的时候
                } else {
                    console.log('数据长度不是单')
                    that.setData({
                        talkIndex: that.data.talkIndex + 1,
                        isRobotSay: !that.data.isRobotSay,
                    }, () => {
                        //只提示一遍
                        if (that.data.talkIndex < 2) {
                            that.setData({
                                isShowChangeUserTip: true,
                            })
                            that.countDowm()
                        } else {
                            console.log('不在显示倒计时')
                        }

                    })
                }
            }
        })
    },
    //获取任务四的数据
    getTaskFourData: function() {
        var dataDic = {
            ModuleId: app.globalData.moduleId,
            TaskMark: 4
        };
        var that = this
        api.methodBasicEnglish_GetTaskData({
            dataDic: dataDic,
            success: function(res) {
                console.log(res.data.data)
                var data = res.data.data.TaskList[0].ListListen
                data.forEach(item => {
                    item.RoleImgUrl = app.globalData.imgUrl + item.RoleImgUrl
                    item.AudioAddress = app.globalData.audioUrl + item.AudioAddress
                })
                that.setData({
                    isShowLoading: true,
                    listenData: data,
                    selectQuestion: res.data.data.TaskList[0].ListAnswer,
                    talkData: data,
                })
                // that.setData({
                //     isShowLoading: true,
                //     listenData: res.data.data.TaskList[0].ListListen,
                //     selectQuestion: res.data.data.TaskList[0].ListAnswer,
                //     talkData: res.data.data.TaskList[0].ListListen,
                // })
                // if (!that.data.isBackOnNext) {
                setTimeout(() => {
                    // innerAudioContext.src = app.globalData.audioUrl + res.data.data.TaskList[0].ListListen[that.data.listenIndex].AudioAddress
                    innerAudioContext.src = data[that.data.listenIndex].AudioAddress
                    innerAudioContext.play()

                }, 1000)
                // }
                var trueArr = []
                for (var i = 0; i < that.data.selectQuestion.length; i++) {
                    trueArr.push(that.data.selectQuestion[i].Answer)
                    that.data.userAnswer.push(null)
                }
                console.log(trueArr, that.data.userAnswer)
                that.setData({
                    trueArr: trueArr
                })
            },
            fail: function(err) {
                console.log('数据请求失败', err)
            }
        })
    },
    //结束任务
    endTask: function() {
        var that = this
        that.endTip.showPopup();
    },
    cancal: function() {
        var self = this
        self.endTip.hidePopup();
    },
    confirm: function() {
        var that = this
        tool.statistics(app.globalData.openId, app.globalData.moduleId, 3, 4, 1)
        app.globalData.isBack = false
        innerAudioContext.offEnded()
        wx.redirectTo({
            url: '../../../../pages/indexPackage/courseList/courseList',
        })
    },
    //听列表点击事件
    listenSource: function(e) {
        var that = this
        console.log(e)
        innerAudioContext.stop();
        var index = e.currentTarget.dataset.index
        var src = e.currentTarget.dataset.src
        that.setData({
            listenIndex: index
        })
        // innerAudioContext.src = app.globalData.audioUrl + that.data.listenData[that.data.listenIndex].AudioAddress
        innerAudioContext.src = that.data.listenData[that.data.listenIndex].AudioAddress
        innerAudioContext.play()
    },
    againTip: function() {
        var that = this
        wx.showModal({
            title: '温馨提示',
            content: '请点击重测按钮再来答题',
            showCancel: false
        })
    },
    //选择答案
    selectAnswer: function(e) {
        var that = this
        console.log(e.currentTarget.dataset.idex)
        console.log(e.currentTarget.dataset.idx)
        var index = e.currentTarget.dataset.idex
        var id = e.currentTarget.dataset.idx
        var arr = 'selectQuestion[' + index + '].OpionList[' + id + '].Status'
        that.data.userAnswer.splice(index, 1, id);
        console.log('------', that.data.userAnswer)
        if (that.data.userAnswer.indexOf(null) < 0) {
            console.log(' 测试')
            that.setData({
                isCanTest: true
            })
        } else {
            console.log('还不能测试')
        }
        if (e.currentTarget.dataset.idex != that.data.titleIndex) {
            console.log(11)
            for (var j = 0; j < that.data.selectQuestion[index].OpionList.length; j++) {
                var arr1 = 'selectQuestion[' + index + '].OpionList[' + j + '].Status'
                that.setData({
                    [arr1]: false
                })
            }
            setTimeout(() => {
                that.setData({
                    titleIndex: index,
                    [arr]: !that.data.selectQuestion[index].OpionList[id].Status,
                })
            }, 10)
        } else {
            console.log(22)
            if (that.data.selectQuestion[index].OpionList[id].Status == false) {
                console.log('++')
                var ind = Math.abs(id - 1)
                for (var j = 0; j < that.data.selectQuestion[index].OpionList.length; j++) {
                    var arr1 = 'selectQuestion[' + index + '].OpionList[' + j + '].Status'
                    that.setData({
                        [arr1]: false
                    })
                }
                setTimeout(() => {
                    that.setData({
                        titleIndex: index,
                        [arr]: !that.data.selectQuestion[index].OpionList[id].Status,

                    })
                }, 100)

            }
        }
        console.log(that.data.titleIndex)
    },
    //开始测试
    beginTest: function() {
        var that = this
        var userAnswerInfo = []
        that.setData({
            isBeginTest: true
        })
        for (var p = 0; p < that.data.userAnswer.length; p++) {
            if (that.data.userAnswer[p] == that.data.trueArr[p]) {
                userAnswerInfo.push(1)
            } else {
                userAnswerInfo.push(0)
            }
        }
        that.setData({
            answerInfo: userAnswerInfo
        })
        console.log(that.data.answerInfo)
        // wx.showLoading({
        //     title: '2秒后进入个模块',
        //     mask:true
        // })
        // setTimeout(()=>{
        //     wx.hideLoading()
        //     that.setData({
        //         selectIndex: that.data.selectIndex + 1,
        //         isShowChangeUserTip: true,
        //         talkIndex: 0
        //     })
        //     that.countDowm()
        // },2000)
    },
    //重新测一遍
    testAgain: function() {
        console.log('在测一遍')
        var that = this
        //数据状态复原
        that.setData({
            isCanTest: false,
            isBeginTest: false,
            answerInfo: [],
            userAnswer: []
        })
        //将返回的数据全部状态还原
        for (var a = 0; a < that.data.selectQuestion.length; a++) {
            that.data.userAnswer.push(null)
            for (var b = 0; b < that.data.selectQuestion[a].OpionList.length; b++) {
                if (that.data.selectQuestion[a].OpionList[b].Status) {
                    var arr2 = 'selectQuestion[' + a + '].OpionList[' + b + '].Status'
                    that.setData({
                        [arr2]: false
                    })
                }
            }
        }
        setTimeout(() => {
            console.log(that.data.selectQuestion)
        }, 2000)
    },
    //进入情景对话
    gotoDialogue: function() {
        var that = this
        that.setData({
            selectIndex: 2,
            isShowChangeUserTip: true,
            talkIndex: 0
        })
        // that.countDowm()
    },
    //选择练习类型
    selecteType: function(options) {
        console.log(options)
        var index = options.currentTarget.dataset.index
        var that = this
        if (index != that.data.selectIndex) {
            that.setData({
                selectIndex: index,
                scrollTop: 0
            })
            //停止音频
            innerAudioContext.stop();
            if (index == 2) {
                that.setData({
                    isShowChangeUserTip: true,
                    talkIndex: 0
                })
                
                // that.countDowm()
            } else {
                //防止录音过程点击其他两个选项，将此变量还原
                that.setData({
                    isRobotSay: true
                })
            }
        }

    },
    //页面提示开始按钮
    tipBegin:function(){
        var that=this
        that.setData({
            isShowChangeUserTip: false,
        })
        setTimeout(() => {
            // innerAudioContext.src = app.globalData.audioUrl + that.data.talkData[that.data.talkIndex].AudioAddress
            innerAudioContext.src = that.data.talkData[that.data.talkIndex].AudioAddress
            innerAudioContext.play()
       }, 210)
    },
    //3秒的倒计时
    countDowm: function() {
        var that = this
        that.timer_record = setInterval(() => {
            that.setData({
                time: that.data.time - 1
            })
            if (that.data.time <= 0) {
                clearInterval(that.timer_record);

                setTimeout(() => {
                    that.setData({
                        time: 5,
                        isShowChangeUserTip: false,
                    })
                }, 200)
                if (that.data.isRobotSay) {
                    setTimeout(() => {
                        // innerAudioContext.src = app.globalData.audioUrl + that.data.talkData[that.data.talkIndex].AudioAddress
                        innerAudioContext.src = that.data.talkData[that.data.talkIndex].AudioAddress
                        innerAudioContext.play()
                    }, 210)
                }
            }
        }, 1000)
    },
    //长按中（录音中）
    longTap: function() {
        console.log('长按中')
        var that = this
        that.setData({
            isLongTap: true
        })

        that.oneSecond = setInterval(() => {
            that.setData({
                oneSecondTime: that.data.oneSecondTime + 1
            })
            console.log(that.data.oneSecondTime)
            if (that.data.oneSecondTime >= 1) {
                console.log('大于一秒了', that.data.oneSecondTime)
                clearInterval(that.oneSecond)
                that.recordStart()
            }
        }, 1000)



    },
    //开始录音（开始长按）
    touchStart: function() {
        console.log('开始长按')
    },
    //结束录音（结束长按）
    touchEnd: function() {
        console.log('结束长按')
        var that = this
        that.setData({
            isLongTap: false
        })
        if (that.data.oneSecondTime < 1) {
            console.log('录音时间过短')
            clearInterval(that.oneSecond)
            wx.showModal({
                title: '录音时间过短',
                content: '请长按录音按钮录音',
                showCancel: false,
                success: (res) => {
                    if (res.confirm) {
                        console.log('用户点击确定')
                        that.setData({
                            timeKeeping: 0,
                            isRobotSay: false,
                            talkIndex: that.data.talkIndex
                        })
                    }
                }
            })
            return
        }
        setTimeout(() => {
            that.recordEnd()
        }, 1000)

    },


    //开始录音
    recordStart() {
        innerAudioContext.stop();
        let that = this;
        console.log('开始录音', that.data.talkData[that.data.talkIndex].EnglishSentence)
        //录音提交参数
        let scoreCfg = {
            coreType: 'sent.eval', //测评类型 
            refText: that.data.talkData[that.data.talkIndex].EnglishSentence, //参考文本 
            scale: 100, //分制 
            precision: 1, //精度 
            dict_type: 'kk', //音素字典选项  
            slack: 1 //宽松度 
        }
        wx.showLoading({
            title: '准备录音中'
        })

        recorder.start({
            duration: 20 * 1000, //录音时长  
            serverParams: scoreCfg, //录音传参
            //开始录音成功回调
            onStart() {
                wx.hideLoading()
                console.log("录音开始onStart");
                that.setData({
                    timeKeeping: 0,
                });
                clearInterval(that.timer);
                let timer = setInterval(function() {
                    that.setData({
                        timeKeeping: that.data.timeKeeping + 1,
                    });
                    console.log('计时', that.data.timeKeeping);
                    // 当超出时间上限时，停止录音
                    if (that.data.timeKeeping == 20) {
                        clearInterval(timer);
                        that.setData({
                            isLongTap: false,
                        })
                    }
                }, 1000);
                that.timer = timer;
            },
            //录音完成回调
            onStop(ret) {
                clearInterval(that.timer);
                console.log('录音完成onStop', ret);
                console.log('录音时间', that.data.timeKeeping);
                that.setData({
                    oneSecondTime: 0
                })
                recorder.stop();
                //录音完成提示震动
                wx.vibrateShort({
                    complete(res) {
                        console.log('录音完成打开震动', res)
                    }
                });
                wx.showLoading({
                    title: '录音处理中'
                })
            },
            //获取评分结果回调
            onScore(ret) {
                wx.hideLoading();
                console.log("录音评分结果onScore", JSON.parse(ret));
                let result = JSON.parse(ret).result;
                app.globalData.result = result;
                if (result) {
                    console.log('得分结果', result);
                    that.setData({
                        score: that.data.score + result.overall, //录音得分
                        integrity: result.integrity, //完整度
                        rhythm: result.fluency, //原来的节律度改为流畅度
                        pronunciation: result.pronunciation, //发音得分
                        timeKeeping: 0,
                        // isRobotSay: true,
                    })
                    if (that.data.talkIndex < that.data.talkData.length - 1) {
                        setTimeout(() => {
                            console.log('还没录完')
                            that.setData({
                                talkIndex: that.data.talkIndex + 1,
                                isRobotSay: true,
                            }, () => {
                                //只提示一遍
                                if (that.data.talkIndex < 2) {
                                    that.setData({
                                        isShowChangeUserTip: true,
                                    })
                                    that.countDowm()
                                } else {
                                    setTimeout(() => {
                                        // innerAudioContext.src = app.globalData.audioUrl + that.data.talkData[that.data.talkIndex].AudioAddress
                                        innerAudioContext.src = that.data.talkData[that.data.talkIndex].AudioAddress
                                        innerAudioContext.play()
                                    }, 210)
                                }
                            })

                        }, 1500)
                    } else {
                        wx.showLoading({
                            title: '正在评分',
                        })
                        setTimeout(() => {
                            console.log('录完')
                            //求平均分然后跳转录音结果页面
                            var score = parseInt(that.data.score * 2 / that.data.talkData.length)
                            var courseName = app.globalData.courseName
                            var scoreStr = '0~20'
                            if (score >= 0 && score <= 20) {
                                scoreStr = '0~20'
                            } else if (score > 20 && score <= 40) {
                                scoreStr = '21~40'
                            } else if (score > 40 && score <= 60) {
                                scoreStr = '41~60'
                            } else if (score > 60 && score <= 80) {
                                scoreStr = '61~80'
                            } else {
                                scoreStr = '81~100'
                            }
                            app.aldstat.sendEvent('口语练习统计', {
                                'coursename': courseName + '-分数-' + scoreStr
                            });
                            mta.Event.stat("KYpractice_score", {
                                'coursename': courseName + '-分数-' + scoreStr
                            });

                            wx.hideLoading()
                            wx.navigateTo({
                                url: '/pages/taskPackage/pages/taskFourResult/taskFourResult?score=' + score,
                            })
                            innerAudioContext.offEnded()
                        }, 1500)
                    }
                } else { //获取得分失败重录
                    wx.hideLoading();
                    wx.showModal({
                        title: '温馨提示',
                        content: 'Ai老师计算失误',
                        showCancel: false,
                        confirmText: '再录一次',
                        success: (res) => {
                            if (res.confirm) {
                                console.log('用户点击确定');
                                wx.hideLoading();
                                that.setData({
                                    timeKeeping: 0,
                                    isRobotSay: false,
                                    talkIndex: that.data.talkIndex
                                })
                            } else if (res.cancel) {
                                console.log('用户点击取消')
                            }
                        }
                    })
                }
            },
            //过程发生错误回调，目前有如下情况会触发：1、录音异常中止 2、远程服务器连接异常中止
            onError(ret) {
                wx.hideLoading();
                console.log("录音过程发生错误回调onError", ret);
                recorder.stop();
                switch (ret.errCode) {
                    case 30001:
                        //还未完成录音服务器就返回报错信息
                        that.onErrorToRecord();
                        break;
                    case 30002:
                        //正在录音时服务器与客户端主动断开，评分服务器出错
                        that.onErrorToRecord();
                        break;
                    case 30003:
                        //客户端网络中断或者其他异常导致客户端主动与服务器断开连接
                        that.onErrorToRecord();
                        break;
                    case 30004:
                        //本地录音机出错，执行错误的停止开始录音流程
                        that.onErrorToRecord();
                        break;
                    default:
                        console.log('error', ret.errMsg)
                }
            },
            fail(ret) {
                console.log("录音接口调用失败fail", ret);
                app.aldstat.sendEvent('进入录音错误回调');
                mta.Event.stat("enter_recoreError");
                wx.hideLoading();
                wx.showModal({
                    title: '温馨提示',
                    content: '录音出了小差错，请重新录制',
                    showCancel: false,
                    success: (res) => {
                        if (res.confirm) {
                            console.log('用户点击确定')
                            that.setData({
                                timeKeeping: 0,
                                isRobotSay: false,
                                talkIndex: that.data.talkIndex
                            })
                        }
                    }
                })
                recorder.stop();
            },
        })

    },
    //录音出错后执行的重录代码
    onErrorToRecord(tip) {
        let that = this;
        wx.showModal({
            title: '温馨提示',
            content: '录音出了差错，请重新录制',
            showCancel: false,
            confirmText: '确定',
            success: (res) => {
                that.setData({
                    timeKeeping: 0,
                    isRobotSay: false,
                    talkIndex: that.data.talkIndex
                })
                recorder.stop();
            },
        })
    },
    // 完成录音
    recordEnd() {
        let that = this;
        console.log("结束录音");
        //录音时间过短
        // if (that.data.timeKeeping < 1) {
        //     clearInterval(that.timer);
        //     console.log("点击时间隔过短")
        //     wx.showModal({
        //         title: '录音时间过短',
        //         content: '请长按录音按钮录音',
        //         showCancel:false,
        //         success: (res) => {
        //             if (res.confirm) {
        //                 console.log('用户点击确定');
        //                 wx.hideLoading();
        //                 that.setData({
        //                    isRobotSay:false,
        //                    timeKeeping: 0,
        //                 })
        //             } else if (res.cancel) {
        //                 console.log('用户点击取消')
        //             }
        //         }
        //     })
        //     return
        // }
        recorder.stop({
            success: (ret) => {
                console.log("skegn_stop success", ret)
            },
            fail: (ret) => {
                console.log("skegn_stop fail", ret)
            },
            complete: (ret) => {
                console.log("skegn_stop complete", ret)
            }
        })


    },
})